import React from 'react';
import ReactDOM from 'react-dom';
import mirror, {actions, connect} from 'mirrorx';
import { ActionSheet, WingBlank, WhiteSpace, Button, Toast, List,Modal } from 'antd-mobile';
const Item = List.Item;
const Brief = Item.Brief;
const AlertPannel = Modal.alert;

const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
    wrapProps = {
        onTouchStart: e => e.preventDefault(),
    };
}

class App extends React.Component { 
	constructor(props) {
		super(props);
        this.state = {
            result:{},
            clicked: 'none',
            isHolder: false,
            isInsure: false,
            coverageList: [],
            hideGuide:true
        }
	}

	componentDidMount(){
        this.policyId = T.urlQuery('id');
        this.requestDetailInfo();
        this.requestFile();
    }

    requestFile = ()=>{
        T.fetch({
            url:'/msg/account/policyListData.json?policyId='+this.policyId,
            method:"get"
        }).then((res)=>{
            if(res.success){              
                let result = res.value || [];
                this.elePolicyUrl = (result[0] ||{}).url;  
            }
        })
    }
   
    requestDetailInfo = () => {
        T.fetch({
            url:'/policy/detail.json',
            data: {
                policyId:this.policyId
            },
            loading:true
        }).then((res)=>{
            if(res.success){              
                let result = res.value || {};
                let obj = res.value.coverageList;
                let coverageList = [];
                for(var i in obj){
                    coverageList.push({
                        planName: i,
                        sumInsured: obj[i]
                    })
                }
                this.policyNo = result.policyNo;
                this.status = result.status;
                this.setState({
                    coverageList,
                    result,
                    holderCust: result.holderCust,
                    insureCust: result.insureCust,
                })
            }
        })
    }

    tranformDate = (dateStr) => {
        if(dateStr == undefined)return;
        return dateStr.split(' ')[0];
    }

    transformName = (list) => {
        if(list.length == 0)return;
        let listName = [];
        list.forEach((item, index)=>{
            listName.push(item.name)
        })
        return listName.join('/');
    }

    transformGender = (type) => {
        const Lang = window.LangMessage ||{};
        let obj = {
            "MALE":	Lang.gender_male || "男性",
            "FMAIL": Lang.gender_female || "女性",
        }
        return obj[type]
    }

    transformCertiType = (type) => {
        const Lang = window.LangMessage ||{};
        let obj = {
            "SHENFENZHENG": Lang.ID_card || "身份证",
            "HUZHAO": Lang.passport || "护照",
            "HUKOUBU": Lang.residence_booklet || "户口簿",
            "JUNGUANZHENG": Lang.military_identity_card || "军人身份证",
            "POLICYID": Lang.armed_police_identity_card || "武装警察身份证",
            "GAJMLAIWANGCERTI": Lang.HK_Macao_to_mainland || "港澳居民来往内地通行证",
            "TAIBAOCERTI": Lang.TW_to_mainland || "台湾居民来往内地通行证",
            "WAIGUORENCERTI": Lang.foreigner_mainland || "外国人永久居留身份证",
        }
        return obj[type]
    }

    transfromRelationEnum = (type) => {
        const Lang = window.LangMessage ||{};
        let obj = {
            "SELF": Lang.self || "本人",
            "SPOUSE": Lang.spouse || "配偶",
            "CHILDREN": Lang.children || "子女",
            "PARENTS": Lang.parents || "父母",
            "OTHER": Lang.other || "其他",
        }
        return obj[type]
    }

    showActionSheet = () => {
        const Lang = window.LangMessage ||{};
        const BUTTONS = [Lang.scan_elec_order || '查看電子保單', 
                        Lang.scan_elec_invoice || '查看電子發票', 
                        Lang.share || '分享', 
                        Lang.surrender || '退保', 
                        Lang.freelook || '犹豫期退保', 
                        Lang.cancel || '取消'];

        ActionSheet.showActionSheetWithOptions({
            options: BUTTONS,
            cancelButtonIndex: BUTTONS.length - 1,
            destructiveButtonIndex: BUTTONS.length - 3,
            ...wrapProps,
        },
        (buttonIndex) => {
            this.setState({ clicked: BUTTONS[buttonIndex] });
            if(buttonIndex ==0){
                if(this.elePolicyUrl){
                    let result = this.elePolicyUrl.match(/^https?\:\/\/([\w\-\.]+)(\/.+)/)||[];
                    let newUrl = result[2] ||"";

                    location.href = "/translateHost" + newUrl;
                }
            }else if(buttonIndex ==1){
                actions.routing.push({pathname:"/invoice-list",search:"?id="+this.policyId})
            }else if(buttonIndex ==2){
                this.setState({hideGuide:false})
            }else if(buttonIndex ==3 ){
                if(this.status =="POLICY_EFFECT"){
                    const {result} = this.state;
                    actions.routing.push({
                        pathname: "surrender-compose",
                        search: `?policyNo=${this.policyNo}`
                    })
                }else if(this.status =="TERMINATION"){
                    AlertPannel("Can not be surrendered once the policy is terminated!","",[
                        { text: 'OK', onPress: () => console.log('ok') },
                       
                      ])
                }else{
                    AlertPannel("Can not surrender!","",[
                        { text: 'OK', onPress: () => console.log('ok') },
                       
                      ])
                }   
            }else if(buttonIndex == 4 ){
                if(this.status =="POLICY_EFFECT"){
                    AlertPannel("Surrender verification","Whether hesitation period surrender?",[
                        { text: 'Cancel', onPress: () => console.log('cancel') },
                        { text: 'Confirm', onPress: () => this.requestTryPrice() },
                      ])
                }else if(this.status =="TERMINATION"){
                    AlertPannel("Can not be surrendered once the policy is terminated!","",[
                        { text: 'OK', onPress: () => console.log('ok') },
                       
                      ])
                }else{
                    AlertPannel("Can not surrender!","",[
                        { text: 'OK', onPress: () => console.log('ok') },
                       
                      ])
                }  
            }
        });
    }

    requestTryPrice = ()=>{
        const {result} = this.state;
        var params={};
        params.posTransType=1;
        params.policyNo=this.policyNo;
        params.posNo="";

        T.fetch({
            url:'/account/preCalculate.json',
            data: params,
            loading:true,
            noTip:true
        }).then((data)=>{
            if (!data.success) {
                AlertPannel("Surrender failed!","",[
                    { text: 'OK', onPress: () => console.log('ok') },
                   
                  ])
               return;
           }

           var feeAmount=data.value.feeAmount;
           var posNo=data.value.posNo;
           this.submitSurrenderConfirm(feeAmount,posNo,this.policyNo);
        })
    }

    submitSurrenderConfirm = (feeAmount,posNo,policyNo)=>{
        var context="your policyNO is :"+policyNo+" which has been successful hesitation period surrender,"
        +"total amount :"+feeAmount+", Money will be returned to your payment account.";
        AlertPannel("surrender",context,[
            { text: 'Cancel', onPress: () => console.log('cancel') },
            { text: 'Confirm', onPress: () => this.submitSurrender(posNo,policyNo) },
          ])
    }

    submitSurrender = (posNo,policyNo)=>{
        var params={};
        params.posTransType=1;
        params.policyNo=policyNo;
        params.posNo=posNo;

        T.fetch({
            url:'/account/submitSurrender.json',
            data: params,
            loading:true,
            noTip:true
        }).then((data)=>{
            if (!data.success) {
                AlertPannel("Surrender failed!","",[
                    { text: 'OK', onPress: () => console.log('ok') },
                  ])
              
           }else{
                this.requestDetailInfo(T.urlQuery('id'));

                AlertPannel("Surrender success!","",[
                    { text: 'OK', onPress: () => console.log('ok') },
                ])
           }
        })
    }

	render() {
        const {result, coverageList, holderCust, insureCust} = this.state;
        const Lang = window.LangMessage ||{};
		return (
            <div className="wrap main">
                <div className="policy-detail">
                    <div className="policy-head">
                            <div className="clearfix p-relative">
                                <p className="fl product-text f30 strong">{result && result.goodNames}</p>
                                <i className="icon-detail-state-1"></i>
                            </div>
                            <div className="pt20 f26" style={{color:'#cdeedf'}}>
                                {`${Lang.policy_no || "保單號"}.  ${result && result.policyNo}`}
                            </div>
                    </div>
                    <div className="box-div">
                            <div className="icon-box"></div>
                    </div>
                    <div className="policy-items">
                        <ul className="bgfw" style={{border:'1px solid #ddd'}}>
                            <li className="clearfix fc9 bor-bottom-dashed f28 policy-li">
                                <span className="fl">{Lang.policy_type || "險種"}</span>
                                <span className="fr">{Lang.policy_amount || "保險金額"}</span>
                                <i className="icon-half-right1"></i>
                                <i className="icon-half-left1"></i>
                            </li>
                            {
                                coverageList.map((item, index)=>{
                                    return (
                                        <li key={index} className="clearfix policy-li">
                                            <span className="fl fc34">{item.planName}</span>
                                            <span className="fr strong">{item.sumInsured}</span>
                                        </li>
                                    )
                                })
                            }
                            {/* <li className="tac pb10"><i className="icon-down"></i></li> */}
                        </ul>
                    </div>

                    <div className="bor-top pl30 pr30 bgfw">
                        <div className="pt20 pb20 bor-bottom detail-items">
                            <span className="fc9 f26 flex-left">{Lang.policy_fee || "保費"}</span>
                            <span className="fc34 f28 flex-right">{result && result.totalInstallPremium}</span>
                        </div>
                        <div className="pt20 pb20 bor-bottom detail-items">
                            <span className="fc9 f26 flex-left">{Lang.coverage_period || "保障期間"}</span>
                            <span className="fc34 f28 flex-right">{`${this.tranformDate(result && result.effectiveDate)} To ${this.tranformDate(result && result.expiryDate)}`}</span>
                        </div>
                        <div className="clearfix pt20 pb20 bor-bottom detail-items" onClick={()=>this.setState({isHolder:!this.state.isHolder})}>
                            <span className="fc9 f26 mt5 flex-left">{Lang.holder || "投保人"}</span>
                            <span className="fc34 f28 flex-right">
                                <i className="icon-right fr"></i>
                                <span className="inline-block mr15">{holderCust && holderCust.name}</span>
                            </span>
                        </div>
                        <div className="clearfix pt20 pb20 pl20" style={{display:this.state.isHolder?'block':'none'}}>
                            <List className="my-list">
                                <Item extra={holderCust && holderCust.name}>{Lang.holder || "投保人"}</Item>
                                <Item extra={holderCust && this.transformGender(holderCust.gender)}>{Lang.gender_text || '性别'}</Item>
                                <Item extra={holderCust && this.tranformDate(holderCust.birthday)}>{Lang.date_of_birth || "出生日期"}</Item>
                                <Item extra={holderCust && this.transformCertiType(holderCust.certiType)}>{Lang.certi_type || "證件類型"}</Item>
                                <Item extra={holderCust && holderCust.certiNo}>{Lang.certi_no || "證件號碼"}</Item>
                                <Item extra={holderCust && holderCust.phone.phoneNo}>{Lang.phone_no || "手機號碼"}</Item>
                                <Item extra={holderCust && holderCust.email.email}>{Lang.email || "郵箱地址"}</Item> 
                            </List>
                        </div>
                        <div className="clearfix pt20 pb20 bor-bottom detail-items" onClick={()=>this.setState({isInsure:!this.state.isInsure})}>
                            <span className="fc9 f26 mt5 flex-left">{Lang.insurant || "被保險人"}</span>
                            <span className="fc34 f28 flex-right">
                                <i className="icon-right fr"></i>
                                <span className="inline-block mr15">{insureCust && this.transformName(insureCust)}</span>
                            </span>
                        </div>
                        <div className="clearfix pt20 pb20 pl20" style={{display:this.state.isInsure?'block':'none'}}>
                            {
                                insureCust && insureCust.map((item, index)=>{
                                    return (
                                        <List key={index} className="my-list">
                                            <Item extra={item.name}>{Lang.insurant || "被保險人"}</Item>
                                            <Item extra={this.transformGender(item.gender)}>{Lang.gender_text || '性别'}</Item>
                                            <Item extra={this.tranformDate(item.birthday)}>{Lang.date_of_birth || "出生日期"}</Item>
                                            <Item extra={this.transformCertiType(item.certiType)}>{Lang.certi_type || "證件類型"}</Item>
                                            <Item extra={item.certiNo}>{Lang.certi_no || "證件號碼"}</Item>
                                            <Item extra={item.phone.phoneNo}>{Lang.phone_no || "手機號碼"}</Item>
                                            {/* <Item extra={this.transfromRelationEnum(item.holderRelation)}>{Lang.relation_with_holder || "與投保人關係"}</Item> */}
                                            <Item extra={item.email.email}>{Lang.email || "郵箱地址"}</Item>
                                        </List>
                                    )
                                })
                            }
                        </div>
                        <div className="clearfix pt20 pb20 bor-bottom detail-items">
                            <span className="fc9 f26 mt5 flex-left">{Lang.policy_items || "保險條款"}</span>
                            <span className="fc34 f28 flex-right">
                                <i className="icon-right fr"></i>
                            </span>
                        </div>
                    </div>

                    <div className="footer">
                        <table>
                            <tbody>
                                <tr>
                                    <td className="bor-right">
                                        <a href="javascript:;" className="f32  tac fcw diy_background">{Lang.submit_claim || "提交索賠"}</a>
                                    </td>
                                    
                                    <td width="50%">
                                        <a href="javascript:;"  onClick={this.showActionSheet} className="f32 tac fcw diy_background" id="moreBtn">{Lang.more || "更多"}</a>
                                    </td> 
                                </tr>
                            </tbody>
                        </table>
                    </div>   
                </div>

                <div className={this.state.hideGuide ? 'none' : 'guide'}>
                    <div className="mask"  onClick={()=>this.setState({hideGuide:true})}>
                        <div className="finger"></div>
                        <button className="btn-close f36">I Know</button> 
                    </div>
                </div>
            </div>
        )
	}
}

export default App;   